package com.apacheGzq.service;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.apacheGzq.pojo.HttpRequest;

/**
 * Created by gaozhiqiang .
 */
public class HttpRqeustParser {
    private static final Logger log = Logger.getLogger(HttpRqeustParser.class);

    public HttpRequest parse(String requestMsg) {
        HttpRequest requestHeader = null;

        String[] requestMsgs = requestMsg.split("\r\n");

        if(requestMsgs.length > 0) {
            requestHeader = new HttpRequest();

            requestHeader.setRequestMethod(requestMsgs[0].split(" ")[0]);
            requestHeader.setRequestURI(requestMsgs[0].split(" ")[1]);
            requestHeader.setHttpVersion(requestMsgs[0].split(" ")[2]);

            for (int i = 1; i < requestMsgs.length ; i++) {
                if(StringUtils.isNotEmpty(requestMsgs[i])) {
                    String[] tmpStrs = requestMsgs[i].split(" ");
                    if(tmpStrs[0].startsWith("Host")) {
                        requestHeader.setHost(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Connection")) {
                        requestHeader.setConnection(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Cache-Control")) {
                        requestHeader.setCacheControl(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Accept")) {
                        requestHeader.setAccept(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Accept-Encoding")) {
                        requestHeader.setAcceptEncoding(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Accept-Language")) {
                        requestHeader.setAcceptLanguage(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("User-Agent")) {
                        requestHeader.setUserAgent(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Content-Length")) {
                        requestHeader.setContentLength(tmpStrs[1]);
                    } else if(tmpStrs[0].startsWith("Cache-Control")) {
                        requestHeader.setCacheControl(tmpStrs[1]);
                    }
                } else {
                    break;
                }
            }
        }

        return requestHeader;
    }
}

